<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>GoIM</title>
    <link rel="stylesheet" href="/static/build/css/layui.css" media="all">
    <style>
        body {
            background-color: #464545;
            background-image: url("//api.isoyu.com/bing_images.php");
        }
    </style>
</head>

<body>
<div id="userInfo" style="display: none">
    <input type="text" name="uid" id="uid">
    <input type="text" name="username" id="username">
</div>
<script src="/static/build/layui.js"></script>
<script>
    //演示代码
    layui.use(['layim', 'layer', 'jquery'], function (layim) {
        layim = layui.layim;
        var $ = layui.jquery;
        var domain = window.location.host;
        let wsuri = "ws://" + domain + "/ws";
        let sock = new WebSocket(wsuri);
        sock.onopen = function () {
            console.log("连接到 " + wsuri);
        };
        sock.onclose = function (e) {
            console.log("连接关闭 (" + e.code + ")");
        };

        layim.config({
            init: {
                url: '/api/panel/msg?username=' +{{.user}} //接口地址（返回的数据格式见下文）
                , type: 'get' //默认get，一般可不填
            }
        });

        //监听发送消息
        layim.on('sendMessage', function (data) {
            let msg = {
                id: data.to.id,
                fromid: data.mine.id,
                username: data.mine.username,
                mine: false,
                avatar: data.mine.avatar,
                content: data.mine.content,
                type: data.to.type
            };
            console.log("最终发送数据:", msg);
            sock.send(JSON.stringify(msg));

            sock.onmessage = function (e) {
                let RetData = JSON.parse(e.data);
                console.log("服务器下发数据:", RetData);
                if (RetData.type === "friend") {
                    if (RetData.id === data.mine.id) {
                        RetData.id = RetData.fromid;
                        layim.getMessage(RetData);
                    }
                } else {
                    if (RetData.fromid !== data.mine.id) {
                        console.log("接受群消息");
                        layim.getMessage(RetData);
                    }
                }
            };
        });

        //监听修改签名
        layim.on('sign', function (value) {
            $.get("/api/info/sign/modify", {username: {{.user}}, sign: value});
        });
    });
</script>
</body>

</html>